//
//  NewFeatureView.swift
//  微博
//
//  Created by admin on 2018/3/26.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit

class NewFeatureView: UIView,UIScrollViewDelegate{
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var okBtn: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    class func newFeatureView() -> NewFeatureView{
         let nib=UINib.init(nibName: "NewFeatureView", bundle: nil)
         let v=nib.instantiate(withOwner: nil, options: nil)[0] as! NewFeatureView
         v.frame=UIScreen.main.bounds
         return v
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        initview()
    }
    
    func initview()  {
        let count=4
        let rect=UIScreen.main.bounds
        
        for i in 0..<count {
            let iv=UIImageView(image: UIImage(named: "newfeature_\(i+1)"))
            //设置每个图像大小（位置一次向后排列，排成一排）
            iv.frame=rect.offsetBy(dx: rect.width * CGFloat(i), dy: 0)
            //添加到滚动视图
            scrollView.addSubview(iv)
        }
        //这里多一页（实现滑到最后自动删除视图）
        scrollView.contentSize=CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.isPagingEnabled=true
        scrollView.bounces=false
        scrollView.showsVerticalScrollIndicator=false
        scrollView.showsHorizontalScrollIndicator=false
        scrollView.delegate=self
        
        okBtn.isHidden=true
        pageControl.numberOfPages=count
        pageControl.isUserInteractionEnabled=false
        //pageControl.addTarget(self, action: #selector(onPageClick), for: .touchUpInside)
    }
    
    @IBAction func onOKBtnClick(_ sender: Any) {
        self.removeFromSuperview()//隐藏删除新特性view
    }
    
    @objc func onPageClick(pageControl: UIPageControl) {
        scrollView.contentOffset.x=CGFloat(pageControl.currentPage) * scrollView.bounds.width
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //计算当前页索引 当前偏移位置除以一页大小等于第几页
        let pageIndex=scrollView.contentOffset.x / scrollView.bounds.width
        if Int(pageIndex) == scrollView.subviews.count {
            self.removeFromSuperview()//隐藏删除新特性view
        }
        //最后页要显示进入按钮
        if Int(pageIndex) == scrollView.subviews.count-1 {
            okBtn.isHidden=false//显示按钮
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         okBtn.isHidden=true
         let index = scrollView.contentOffset.x / scrollView.bounds.width
        if Int(index) == scrollView.subviews.count {
           pageControl.isHidden = true
        }else{
           pageControl.currentPage=Int(index)
        }
    }
    

}
